import React, { useEffect, useState } from 'react';
import { Table, Form, Select, Button, Typography, Flex } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { transformArray, download } from '../../../utils/commonUtil';
import { APPROVAL_STATUS } from '../../../utils/constant';
import { apiExperimentalDataSummaryFilter, apiExperimentalDataSummaryList, apiExperimentalDataSummaryDownload} from '../../../services/experimentalData/summary';

const { Title } = Typography;
const ExperimentalDataSummary = () => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const { APPROVED } = APPROVAL_STATUS;

  // 分页相关
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalPage, setTotalPage] = useState();
  // list 页面数据
  const [dataList, setDataList] = useState();
  // 下拉框数据
  const [buList, setBuList] = useState([]);
  const [productList, setProductList] = useState([]);
  const [projectList, setProjectList] = useState([]);
  const [componentList, setComponentList] = useState([]);
  const [columnList, setColumnList] = useState([]);
  const [statusList, setStatusList] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const columnsFirst = [
    {
      title: t('common.bu'),
      dataIndex: 'buType',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.status'),
      dataIndex: 'requestStatus',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.project'),
      dataIndex: 'projectName',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.product'),
      dataIndex: 'productName',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.componment'),
      dataIndex: 'componentName',
      width: 100,
      align: 'center'
    }
  ];
  const [columns, setColumns] = useState(columnsFirst);

  const serach = () => {
    setCurrentPage(1);
    queryList(1);
    const formData = form.getFieldsValue();
    const columnData = formData.columns?.includes('All') ? columnList?.map(item => { if (item.value !== 'All') return item.value }) : formData?.columns || [];
    const columnsSecond = columnData.map(item => {
      return {
        title: item,
        width: 150,
        align: 'center',
        render: (i) => {
          return (
            <div> {i.column[item]} </div>
          )
        }
      };
    });
    const mergeColumns = columnsFirst.concat(columnsSecond);
    setColumns(mergeColumns);
  };

  const getQueryParams = () => {
    const formData = form.getFieldsValue();
    const params = {
      buTypes: formData?.buTypes || [],
      projectNames: formData?.projectNames || [],
      productNames: formData?.productNames || [],
      componentNames: formData?.componentNames || [],
      requestStatus: formData?.requestStatus || []
    };
    return params;
  };

  // 获取页面list数据
  const queryList = async (pagination, size) => {
    const params = {
      ...getQueryParams(),
      page: pagination || currentPage,
      limit: size || pageSize
    };
    apiExperimentalDataSummaryList(params).then((res) => {
      setDataList(res?.data?.data?.items);
      setTotalPage(res?.data?.data?.total);
    });
  };

  // 调用下拉框api
  const apiSelectAsync = async () => {
    apiExperimentalDataSummaryFilter().then((res) => {
      if (res?.data?.code === 200) {
        setBuList(transformArray(res?.data?.data?.buType));
        setProjectList(transformArray(res?.data?.data?.projectName));
        setProductList(transformArray(res?.data?.data?.productName));
        setComponentList(transformArray(res?.data?.data?.componentName));
        setStatusList(transformArray(res?.data?.data?.requestStatus));
        setColumnList([{
          value: "All",
          label: "All"
        },
        ...transformArray(res?.data?.data?.column)])
      }
    });
  };

  const downloadHandle = () => {
    const downloadFileIds = selectedRows?.map((item)=>{
      return{
        experimentalProjectId:item.experimentalProjectId,
        experimentalProductId:item.experimentalProductId,
        experimentalComponentId:item.experimentalComponentId
      }
    });
    // 初始化新数组
    const experimentalProjectIds = [];
    const experimentalProductIds = [];
    const experimentalComponentIds = [];

    // 遍历downloadFileIds数组
    downloadFileIds.forEach(item => {
        experimentalProjectIds.push(item.experimentalProjectId);
        experimentalProductIds.push(item.experimentalProductId);
        experimentalComponentIds.push(item.experimentalComponentId);
    });
    const params = {
      experimentalProjectIds,
      experimentalProductIds,
      experimentalComponentIds
    };
    apiExperimentalDataSummaryDownload(params).then((res) => {
      if (res?.data) {
        download(res)
      }
    })
  };

  const onSelectChange = (newSelectedRowKeys, selectedRows) => {
    // console.log('selectedRows changed: ', selectedRows);
    setSelectedRows(selectedRows);
  };

  const getRowKey = (record) => {
    return record.experimentalProjectId + record.experimentalProductId + record.experimentalComponentId;
  };

  useEffect(() => {
    // 调用页面list api
    queryList();
    // 调用下拉框api
    apiSelectAsync();
  }, [])

  return (
    <>
      <div className='page-title-wrap'>
        <Flex align='center' justify='space-between'>
          <Title className='fontStyleH2' level={2} >{t('experimentalData.experimentalDataSummary')}</Title>
          <Button disabled={selectedRows?.length === 0} onClick={() => { downloadHandle() }}>{t('common.download')}</Button>
        </Flex>
      </div>
      <div className='page-content-wrap'>
        <Form form={form} className='filter-wrap'>
          <Flex align='center' gap="middle">
            <Form.Item name="buTypes"  label={t('common.bu')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={buList} />
            </Form.Item>
            <Form.Item name="requestStatus" initialValue={[APPROVED]}  label={t('common.status')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={statusList} />
            </Form.Item>
            <Form.Item name="projectNames"  label={t('common.project')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={projectList} />
            </Form.Item>
            <Form.Item name="productNames"  label={t('common.product')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={productList} />
            </Form.Item>
            <Form.Item name="componentNames"  label={t('common.componment')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={componentList} />
            </Form.Item>
            <Form.Item name="columns"  label={t('common.column')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={columnList} />
            </Form.Item>
            <Button
              className='search-btn'
              type="primary"
              onClick={serach}
              icon={<SearchOutlined style={{ fontSize: 20 }} />}
            />
          </Flex>
        </Form>
        <Table
          rowSelection={{
            onChange: onSelectChange,
          }}
          columns={columns}
          dataSource={dataList}
          size='small'
          rowKey={getRowKey}
          scroll={{ x: 1500, y: 'calc(100vh)' }}
          pagination={{
            total: totalPage,
            current: currentPage,
            pageSize: pageSize,
            onChange: (_crrentPage, _pageSize) => {
              setCurrentPage(_crrentPage);
              setPageSize(_pageSize);
              queryList(_crrentPage, _pageSize);
            },
            pageSizeOptions: [10, 20, 50],
            showSizeChanger: true,
            showTotal: (total) => {
              return `Total ${total} items`;
            },
          }}
        />
      </div>
    </>
  )
};

export default ExperimentalDataSummary;
